import React, { Component } from "react"
import styles from "./index.module.scss"
import { Card, Form, Breadcrumb, Button, Space, Input, Radio, Modal, Upload, message } from "antd"
import { PlusOutlined } from "@ant-design/icons"

import { Link } from "react-router-dom"
import Channel from "components/Channel"
// 导入富文本编辑器
import ReactQuill from "react-quill"
import "react-quill/dist/quill.snow.css"
// 导入基础路径
import { baseURL } from "utils/request"
import { addAritcle, getArticleById, updateArticle } from "api/article"
export default class ArticlePublish extends Component {
  state = {
    // 控制封面图
    type: 1,
    // 存放上传的文件列表
    fileList: [],
    // 控制图片预览弹窗
    previewVisible: false,
    // 预览图片地址
    previewUrl: "",
    // 编辑的id
    id: this.props.match.params.id
  }
  formRef = React.createRef()
  render() {
    // console.log(this.props.match.params.id)
    const { id } = this.state
    return (
      <div className={styles.root}>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>{id ? "编辑文章" : "发布文章"}</Breadcrumb.Item>
            </Breadcrumb>
          }>
          <Form
            labelCol={{ span: 4 }}
            size="large"
            onFinish={this.onFinish}
            validateTrigger={["onChange", "onBlur"]}
            initialValues={{ content: "", type: this.state.type }}
            ref={this.formRef}>
            <Form.Item
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: "文章标题不能为空"
                }
              ]}>
              <Input placeholder="请输入文章标题" style={{ width: 400 }}></Input>
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[
                {
                  required: true,
                  message: "请选择频道"
                }
              ]}>
              <Channel theme="snow" placeholder="请输入文章内容..."></Channel>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.changeImageType}>
                <Radio value={0}>无图</Radio>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>
            {/* 上传组件 */}
            <Form.Item wrapperCol={{ offset: 4 }}>
              {this.state.type !== 0 && (
                // fileList:控制文件列表
                // action:控制上传地址 name用户指定名字
                <Upload
                  name="image"
                  listType="picture-card"
                  fileList={this.state.fileList}
                  action={`${baseURL}upload`}
                  onChange={this.uploadImages}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}>
                  {this.state.fileList.length < this.state.type && <PlusOutlined />}
                </Upload>
              )}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[
                {
                  required: true,
                  message: "文本内容不能为空"
                }
              ]}>
              <ReactQuill></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button type="primary" htmlType="submit" size="large">
                  {id ? "编辑文章" : "发布文章"}
                </Button>
                <Button type="primary" size="large" onClick={this.addDraft}>
                  {" "}
                  保存草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        {/* 图片预览弹窗 */}
        <Modal
          visible={this.state.previewVisible}
          title="图片预览"
          footer={null}
          onCancel={this.handleCancel}>
          <img src={this.state.previewUrl} alt="example" style={{ width: "100%" }} />
        </Modal>
      </div>
    )
  }
  async componentDidMount() {
    if (this.state.id) {
      const res = await getArticleById(this.state.id)
      console.log(res.data)
      const type = res.data.cover.type
      const images = res.data.cover.images.map(item => {
        return {
          url: item
        }
      })
      // 表单数据回显
      const values = {
        ...res.data,
        type
      }
      this.formRef.current.setFieldsValue(values)

      // 处理图片回显
      this.setState({
        fileList: images,
        type
      })
    }
  }
  // 改变图类型
  changeImageType = e => {
    // console.log(e.target.value)
    this.setState({
      type: e.target.value,
      // 清空fileList
      fileList: []
    })
  }
  // 提交文章
  onFinish = async values => {
    this.save(values, false)
    // 成功

    this.props.history.push("/home/list")
  }

  // 提交文章
  save = async (values, draft) => {
    const { fileList, type } = this.state
    if (fileList.length !== type) {
      return message.warn("图片文章不正确")
    }
    const images = fileList.map(item => {
      return item.url || item.response.data.url
    })
    // 有id就是编辑
    if (this.state.id) {
      // 编辑文章
      await updateArticle(
        {
          ...values,
          cover: {
            type,
            images
          }
        },
        draft
      )
      message.success("编辑文章成功")
    } else {
      // 添加文章
      await addAritcle(
        {
          ...values,
          cover: {
            type,
            images
          }
        },
        draft
      )
      message.success("添加文章成功")
    }
  }
  // 保存草稿
  addDraft = async () => {
    const values = await this.formRef.current.validateFields()
    // console.log(values)
    this.save(values, true)

    message.success("保存草稿成功")
    this.props.history.push("/home/list")
  }
  // 获取上传成功的图片地址
  uploadImages = ({ file, fileList }) => {
    // console.log(fileList)
    this.setState({
      fileList
    })
  }
  // 点击文件链接或预览图标时的回调
  handlePreview = file => {
    console.log(file)
    const url = file.url || file.response.data.url
    this.setState({
      previewVisible: true,
      previewUrl: url
    })
  }
  // 图片弹层事件
  handleCancel = () => {
    this.setState({
      previewVisible: false
    })
  }

  // beforeUpload图片上传前
  beforeUpload = file => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png"
    if (!isJpgOrPng) {
      message.error("只能上传 JPG/PNG file!")
      return Upload.LIST_IGNORE
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error("上传的图片不能超过 2MB!")
      return Upload.LIST_IGNORE
    }
    return true
  }
}
